﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Sharp.Infrastructure.Crosscutting;

namespace Sharp.Portal.Mvc.Filter
{
    [DebuggerStepThrough]
    public class CustomHandleErrorAttribute : HandleErrorAttribute
    {
        public CustomHandleErrorAttribute()
            : base()
        {
        }


        public override void OnException(ExceptionContext filterContext)
        {
            if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
            {
                return;
            }
            if (filterContext.HttpContext?.Request?.AcceptTypes == null)
            {
                return;
            }

            if (filterContext.HttpContext.Request.IsAjaxRequest() &&
                filterContext.HttpContext.Request.AcceptTypes.All(x => !x.Equals("text/html", StringComparison.CurrentCultureIgnoreCase)))
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        data = new string[] { },
                        errors = filterContext.Exception.Message
                    }
                };
            }
            else
            {

                var controllerName = (string)filterContext.RouteData.Values["controller"];
                var actionName = (string)filterContext.RouteData.Values["action"];
                var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
                filterContext.Result = new ViewResult
                {
                    ViewName = "Error",//View,
                    MasterName = Master,
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                    TempData = filterContext.Controller.TempData
                };

            }
            
            LogHelper.Error(filterContext.Exception);
#if DEBUG
            filterContext.ExceptionHandled = false;
#else
            filterContext.ExceptionHandled = true;
#endif
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 200;

            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }
}